package com.yunfangdata.shiro;


import com.yunfangdata.domain.Employee;
import com.yunfangdata.domain.Role;
import com.yunfangdata.service.IEmployeeService;
import com.yunfangdata.service.IPermissionService;
import com.yunfangdata.service.IRoleService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

public class UserRealm extends AuthorizingRealm {

    @Autowired
    private IEmployeeService employeeService;
    @Autowired
    private IRoleService roleService;
    @Autowired
    private IPermissionService permissionService;

    @Override
    public String getName() {
        return "UserRealm";
    }
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {




        //获取当前 发送登录请求用户
        String uname = (String) token.getPrincipal();
        //判断用户名是否存在
        Employee currentUser = null;
        try {
            currentUser = employeeService.queryCurrentUserByEmpUsername(uname);
        } catch (Exception e) {
            e.printStackTrace();
        }

        if(currentUser.getState()==0){
           throw  new UnknownAccountException("账号不存在");
        }


        if(currentUser == null){
            return null;
        }
        System.out.println(currentUser);
        //交给 shiro执行判断
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(currentUser, currentUser.getPassword(),ByteSource.Util.bytes(currentUser.getUsername()),getName());
        return info;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //获取当前登录用户
        Employee currentUser = (Employee) principals.getPrimaryPrincipal();

        List<String> roleSns = new ArrayList<>();
        List<String> resources = new ArrayList<String>();

        //判断是否是超级管理员
        if(currentUser.isAdmin()){
            roleSns.add("Admin MGR");
            resources.add("*:*");
        }else {
            //查询用户角色
            List<Role> roles = roleService.queryEmpForRoles(currentUser.getId());
            if(roles!=null || roles.size()==0){
                for (Role role : roles) {
                    roleSns.add(role.getSn());
                }
            }
            resources=permissionService.queryResourceByEmployeeId(currentUser.getId());
        }
        //交给shiro框架 完成授权
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        authorizationInfo.addRoles(roleSns);
        authorizationInfo.addStringPermissions(resources);
        return authorizationInfo;

    }
}